#!/usr/bin/env node
const https = require('https'),
      log = console.log,
      cheerio = require('cheerio'),
      addr = 'https://maoyan.com/films?showType=3',
      fs = require('fs'),
      url =require('url'),
      http = require('http'),
      qs = require('querystring');
let list = [];

  
let opt = (ad)=>{
  let p = url.parse(ad);
  p.headers = {
    'User-Agent' :'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/5    37.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',
    'Cookie':' __mta=246660027.1604280921308.1604280921308.1604284611055.2; uuid_n_v=v1; uuid=A83C6DD 01CAB11EB969E4F42DC4C059E12D0E669CE79432E9B2A915AA3B235F7; _lxsdk_cuid=175869827edc8-0739d02b2f30f5-c781f38-144000-175869827edc8; _lxsdk=A83C6DD01CAB11EB969E4F42DC4C059E12D0E669CE79432E9B2A915AA3B235F7; __mta=246660027.1604280921308.1604284611055.1604296559991.3; _csrf=5933a62792f847e545ae402c27ce91ba531b704cdf62f7901fc0f099e97f6157; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1604280918,1604474920; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1604474920; _lxsdk_s=17592285e22-73-2a3-b84%7C%7C2',
    'sec-ch-ua':' "Chromium";v="86", "\"Not\\A;Brand";v="99", "Google Chrome";v="86"',
    'sec-ch-ua-mobile':'?0',
    'Sec-Fetch-Dest':'document',
    'Sec-Fetch-Mode':'navigate',
    'Sec-Fetch-Site':'cross-site',
    'Sec-Fetch-User':'?1',
  };
  return p;
}
function getPage(){
  let html = fs.readFileSync('./index.html').toString('utf8');
  return html;
}

http.createServer((req,res)=>{


  
  if(req.url === '/'){
    res.end(getPage());

  }
  if(req.url === '/getlist'){
    res.end(JSON.stringify(list));
  }
  //let data = '';
  //req.on('data',chunk=>data += chunk);
  //req.on('end',()=>{
    //let item = qs.parse(data).item;
    //if(item !== '' && typeof item !== 'undefined')items.push(item);
    //res.writeHead(200,{
        //'Content-Type':'text/html',
        //'Content-Length':Buffer.byteLength(getPage())
    //});
    //res.end(getPage());
  //});

}).listen(8080);
  


https.get(opt(addr),(res)=>{

  let infm = [];
  let data = '';
  res.on('data',(chunk)=>data+=chunk);
  res.on('end',()=>{
    let $ = cheerio.load(data);
    //log($)
    let courses1 = $('body').find('div.channel-detail-orange');
    //let courses3 = $('body').find('div.channel-detail-orange>i.fraction');
    
    let courses2 = $('body').find('div.movie-item-title>a');
    
    for(let i=0;i<courses2.length;i++){
      let obj = {};
      let movieid = $(courses2[i]).attr('data-val');
      let id = movieid.slice(9,movieid.length);
      id = id.replace('}','');
      obj.movieId = id;
      obj.movieName = $(courses2[i]).text();
      obj.movieRange = $(courses1[i]).text();
      //list.push(obj);
      list.push(obj);
    }
    //list = infm;
    //log(infm);
    //log(list);
    
    

    
  });
  
});



